﻿package little.bunny;

import java.util.Calendar;
import java.util.Date;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnKeyListener;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import android.widget.TableLayout;  
import android.widget.TableRow; 
import android.widget.TableRow.LayoutParams; 

import android.app.DatePickerDialog;  
import android.app.Dialog;  
import android.app.ProgressDialog;
import android.os.Message;  
import android.widget.DatePicker;  

public class CustomXiaoFei extends Activity {
	private Button backButton;
	private Button btnxiaofei;
	private TextView textCardNo;
	
	private EditText txtDate = null;  
	private Button pickDate = null;  
    private static final int DATE_DIALOG_ID = 1;  
    private static final int SHOW_DATAPICK = 0;  
    private int mYear;  
    private int mMonth;  
    private int mDay;  
    //private Button myButton;
    
	private final String serviceNameSpace = "http://littlebunny.com/";
	private final String method_name = "GetCustCardXiaoFei";
	private final String serviceUrl = "http://www.littlebunny.com.cn/bunny_service/bunny_service.asmx";
	private final String SOAP_ACTION = "http://littlebunny.com/GetCustCardXiaoFei";
        
	private int[] ColumnWidths = new int[]{30, 35, 35};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.custom_xiaofei);
		
		//SharedPreferences sharedata = getSharedPreferences("user_data", 0);  
		//String s_card = sharedata.getString("card", null);
		Bundle bundle = new Bundle();
		bundle = this.getIntent().getExtras();
		String s_card = bundle.getString("KEY_CARD");
		
		textCardNo = (TextView) findViewById(R.id.txtCard_No);
		textCardNo.setText(s_card);

		//**********测试数据***************
		//txtInputCard.setText("0755018369");
		//txtInputPass.setText("1220101");
		//*************************
				
		
		init_header();
		
		txtDate = (EditText) findViewById(R.id.editDate1);  
		pickDate = (Button) findViewById(R.id.but_showDate);  
	    pickDate.setOnClickListener(new DateButtonOnClickListener());  
	    final Calendar c = Calendar.getInstance();  
	    mYear = c.get(Calendar.YEAR);  
	    mMonth = c.get(Calendar.MONTH);  
	    mDay = c.get(Calendar.DAY_OF_MONTH);
	    //初始化日期
	    InitDateTime();  
		//getcustomxiaofei();
		
		backButton = (Button) findViewById(R.id.back_button);
		backButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		
		btnxiaofei=(Button)findViewById(R.id.btnsearch_xiaofei);
		btnxiaofei.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				get_custom_xiaofei();
			}
		});
	       
	}
	
	private void get_custom_xiaofei()
	{
		if (NetFunction.CheckNetStatus(this)==false)
		{
			show_info_data("没有找到网络");
			return;
		}
		
		show_info_data("");
		//txtinfo.setText("开始从服务器读取会员消费记录...");

		Toast.makeText(this, "从服务器读取会员消费记录...", Toast.LENGTH_LONG).show();
		
		final ProgressDialog progressDialog = ProgressDialog.show(this, "请稍等",
				"数据加载中...", true);
		
		progressDialog.setOnKeyListener(new OnKeyListener() {
			
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if (keyCode == KeyEvent.KEYCODE_BACK){
					progressDialog.dismiss();
				}
				return false;
			}
		});
		
		Thread networkThread = new Thread() {
			@Override
			public void run() {
				SharedPreferences sharedata = getSharedPreferences("user_data", 0);  
				
				String s_pass = sharedata.getString("pass_key", null);
				
				TextView txtdate1 = (EditText) findViewById(R.id.editDate1);
				
				SoapObject request = new SoapObject(serviceNameSpace, method_name);
				request.addProperty("card_id", textCardNo.getText().toString());
				request.addProperty("u_pass", s_pass);
				request.addProperty("dt_start", txtdate1.getText().toString());

				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
				envelope.dotNet = true;
				envelope.setOutputSoapObject(request);
				
				try {
					HttpTransportSE ht = new HttpTransportSE(serviceUrl);
					ht.call(SOAP_ACTION, envelope);

					final SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
					final String result = response.toString();
					
					// Toast.makeText(this, "读取完毕.", Toast.LENGTH_LONG).show();

					progressDialog.dismiss();
					
					runOnUiThread(new Runnable() {
						public void run() {
							if (result.startsWith("99:", 0))
							{
								show_info_data(result.substring(3));
							}
							else
							{
								show_data(result);
							}
						}
					});
				} catch (Exception e) {
					progressDialog.dismiss();
					e.printStackTrace();
					show_info_data("网络错误");
				}
			}
		};

		networkThread.start();
		
	}
	
	// run when the button is clicked  
    private void show_data(String result_data) {  
    	String[] temp = null; 
    	int fixedRowHeight = 30;
    	
    	TableLayout table = (TableLayout) findViewById(R.id.TableLayout02);
    	table.removeAllViews();
    	
    	if ((result_data.indexOf("|")==-1) && (result_data.indexOf("~")==-1))
    	{
    		show_info_data(result_data);
    		return;
    	}
    	
    	try
    	{
    		temp = result_data.split("\\|");  
        	
        	int len = temp.length;
        	
            for (int i = 0; i < len; i++) {
            	//String s1="10.6~0.02~2012-10-10-20~C186045454";
            	String[] d_row = temp[i].split("~");
            	
            	TableRow row = new TableRow(this);
            	
                //row.setBackgroundDrawable(drawable);
                
                row.addView(makeTableRowWithText(d_row[0], ColumnWidths[0],fixedRowHeight));
                row.addView(makeTableRowWithText(d_row[1], ColumnWidths[1],fixedRowHeight));
                row.addView(makeTableRowWithText(d_row[2], ColumnWidths[2],fixedRowHeight));
                
            	table.addView(row,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            	
            	//画横线
            	View v = new View(this);
                v.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1));
                v.setBackgroundColor(Color.WHITE);
                table.addView(v);
            }
    	}
    	catch (Exception e) {
			e.printStackTrace();
			show_info_data(e.getMessage());
		}
    }
    
    private void show_info_data(String info_msg)
    {
    	TableLayout table = (TableLayout) findViewById(R.id.TableLayout02);
    	table.removeAllViews();
    	
    	if (info_msg == "")
    		return;
    	
    	TableRow row = new TableRow(this);
    	
        row.addView(makeTableRowWithText(info_msg, ColumnWidths[0],30));
        
    	table.addView(row,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    	
    	//画横线
    	View v = new View(this);
        v.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1));
        v.setBackgroundColor(Color.WHITE);
        table.addView(v);
    }
    
    private void init_header()
    {
    	TableRow.LayoutParams wrapWrapTableRowParams = new TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);  
    	wrapWrapTableRowParams.setMargins(1, 3, 1, 1);
    	
        //int[] scrollableColumnWidths = new int[]{20, 20, 20, 30, 30};  
        int fixedRowHeight = 25;  
           
        TableRow row = new TableRow(this);  
        
        TableLayout header = (TableLayout) findViewById(R.id.table_header);
        
        row.setLayoutParams(wrapWrapTableRowParams);  
        row.setGravity(Gravity.CENTER);
        
        Resources resource = this.getBaseContext().getResources();
		Drawable drawable=resource.getDrawable(R.drawable.test_list_bg);
        row.setBackgroundDrawable(drawable);
                
        row.addView(makeTableRowWithText("日期", ColumnWidths[0],fixedRowHeight));
        row.addView(makeTableRowWithText("卡消费金额", ColumnWidths[1],fixedRowHeight));  
        row.addView(makeTableRowWithText("洗衣单号", ColumnWidths[2],fixedRowHeight));
        
        header.addView(row);
    }
    
    private TextView recyclableTextView;
    
    private TextView makeTableRowWithText(String text, int widthInPercentOfScreenWidth,int row_height ) {  
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        
        recyclableTextView = new TextView(this);  
        recyclableTextView.setText(text);
          
        recyclableTextView.setTextColor(Color.BLACK);  
        //recyclableTextView.setTextSize(13);  
        recyclableTextView.setWidth(widthInPercentOfScreenWidth * screenWidth / 100);  
        //recyclableTextView.setHeight(row_height);
                
        return recyclableTextView;  
    }
    

	private void InitDateTime() {
       final Calendar c = Calendar.getInstance();
       c.setTime(new Date());
       c.set(Calendar.DATE, c.get(Calendar.DATE) - 30); //一个月前的日期
              
       mYear = c.get(Calendar.YEAR);
       mMonth = c.get(Calendar.MONTH);
       mDay = c.get(Calendar.DATE);  
       
       updateDisplay();  
	 }
	
	/*
     * 更新日期 
    */  
    private void updateDisplay() {
    	mMonth= mMonth + 1;//monthOfYear这个参数是从0开始的
    	
    	txtDate.setText(new StringBuilder().append(mYear + "-").append(  
              (mMonth) < 10 ? "0" + (mMonth) : (mMonth)).append("-").append(  
              (mDay < 10) ? "0" + mDay : mDay));
    	//Toast.makeText(this, "Year:" + mYear +",Month:"+mMonth +",Day:" + mDay, Toast.LENGTH_LONG).show();
        
    }
    
    /* 
     * 日期控件的事件 
    */  
    private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {  
       public void onDateSet(DatePicker view, int year, int monthOfYear,  
              int dayOfMonth) {  
           mYear = year;  
           mMonth = monthOfYear;
           mDay = dayOfMonth;  
           updateDisplay();  
       }  
    };  
   
    /* 
     * 选择日期Button的事件处理 
     * 
     * @author Raul 
     * 
    */  
    class DateButtonOnClickListener implements  
           android.view.View.OnClickListener {  
       
       public void onClick(View v) {  
           Message msg = new Message();  
           if (pickDate.equals((Button) v)) {  
              msg.what = CustomXiaoFei.SHOW_DATAPICK;
              showDialog(DATE_DIALOG_ID); 
           }  
           //CustomXiaoFei.this.saleHandler.sendMessage(msg);
           
       }  
    }  
  
    @Override  
    protected Dialog onCreateDialog(int id) {  
       switch (id) {  
       case DATE_DIALOG_ID:  
           return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);  
       }  
       return null;  
    }  
  
    @Override  
    protected void onPrepareDialog(int id, Dialog dialog) {  
    	switch (id) {  
   			case DATE_DIALOG_ID:  
   				((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);  
  
           break;  
  
    	}  
    }  
}
